#!/usr/bin/env python

#--------------------------------------
#This demos properly clean up resources allocated in case 
#of exceptions.
#-------------------------------------

poem = '''\
知人者智
自知者明
胜人者有力
自胜者强
'''

f = open('poem.txt', 'w')
f.write(poem)
f.close()

# Manner I. Read file using 'with' statement.
# 'with' statement close the file opened automatically after executing 'with' statement.
# If exception occurs, it closes the file opened always.
with open('poem.txt') as file:
	for line in file:
		print (line, end='')

# Manner II. Read file using 'try' and 'except' block.
# We allocate resources inside try block, and release them 
# inside finally block.
try:
	file = open('poem.txt')
	while True:
		line = file.readline()
		if len(line) == 0:
			break
		print(line, end='')
except KeyboardInterrupt:
	print('!! You calcelled reading from file')
finally: #This block is always executed.
	file.close()
	print('Clean up. Close the file')
